package model.dao;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class BaseDao {

    private static DataSource dataSource;

    static
    {
        //读取资源文件，获取连接参数
        Properties properties=new Properties();
        //通过类加载器读取资源文件
        InputStream is=BaseDao.class.getClassLoader().getResourceAsStream("druid.properties");
        try {
            properties.load(is);
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            dataSource= DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //获取连接池
    public static DataSource getDataSource()
    {
        return dataSource;
    }

    //获取数据库连接
    public static Connection getConnection() throws SQLException {

        return dataSource.getConnection();
    }

    //释放资源
    public static void close(Statement statement,Connection connection)
    {
       close(null,statement,connection);
    }
//重载方法
    public static void close(ResultSet resultSet,Statement statement, Connection connection)
    {
        if(resultSet!=null)
        {
            try {
                resultSet.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }

        if(statement!=null)
        {
            try {
                statement.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if(connection!=null)
        {
            try {
                connection.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }


}
